package com.algrithom.unionfind;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 并查集 547——朋友圈
 *
 * @author think
 * @version 1.0.0
 * @since 2020/2/3
 */
public class Solution1 {
    
    public static void main(String[] args){
        int[][] array = {{1,1,0},{1,1,0},{0,0,1}};
        System.out.println(findCircleNum1(array));
        System.out.println(findCircleNum2(array));
        System.out.println(findCircleNum3(array));
    }
    
    public static void dfs(int[][] array,int[] visited,int i){
        for (int j = 0; j < array.length; j++) {
            if (array[i][j] == 1 && visited[j] == 0) {
                visited[j] = 1;
                dfs(array,visited,j);
            }
        }
    }
    
    public static int findCircleNum1(int[][] array){
        int[] visited = new int[array.length];
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (visited[i] == 0) {
                dfs(array,visited,i);
                count++;
            }
        }
        return count;
    }
    
    public static int findCircleNum2(int[][] array){
        int[] visited = new int[array.length];
        int count = 0;
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < array.length; i++) {
            if (visited[i] == 0) {
                queue.add(i);
                while (!queue.isEmpty()) {
                    int s = queue.poll();
                    visited[s] = 1;
                    for (int j = 0; j < array.length; j++) {
                        if (array[s][j] == 1 && visited[j] == 0) {
                            queue.add(j);
                        }
                    }
                }
                count++;
            }
        }
        return count;
    }
    
    static int find(int[] parent,int i){
        if (parent[i] == -1) {
            return i;
        }
        return find(parent,parent[i]);
    }
    
    static void union(int[] parent,int x,int y){
        int xset = find(parent,x);
        int yset = find(parent,y);
        if (xset != yset) {
            parent[xset] = yset;
        }
    }
    
    public static int findCircleNum3(int[][] array){
        int[] parent = new int[array.length];
        Arrays.fill(parent,-1);
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                if (array[i][j] == 1 && i != j) {
                    union(parent,i,j);
                }
            }
        }
        int count = 0;
        for (int value : parent) {
            if (value == -1) {
                count++;
            }
        }
        return count;
    }
}
